package com.wgh.search.config;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.indices.CreateIndexRequest;
import co.elastic.clients.elasticsearch.indices.CreateIndexResponse;
import co.elastic.clients.elasticsearch.indices.ExistsRequest;
import co.elastic.clients.json.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 索引初始化器
 * 在应用启动时初始化Elasticsearch索引
 */
@Component
public class IndexInitializer implements ApplicationRunner {
    
    @Autowired
    private ElasticsearchClient esClient;
    
    @Value("${elasticsearch.index.product}")
    private String productIndex;
    
    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 检查索引是否存在
        if (!indexExists(productIndex)) {
            // 创建索引
            createProductIndex();
        }
    }
    
    /**
     * 检查索引是否存在
     */
    private boolean indexExists(String indexName) throws IOException {
        ExistsRequest request = new ExistsRequest.Builder()
                .index(indexName)
                .build();
        return esClient.indices().exists(request).value();
    }
    
    /**
     * 创建商品索引
     */
    private void createProductIndex() throws IOException {
        // 构建索引映射
        String mappings = buildProductMapping();
        
        // 创建索引请求
        CreateIndexRequest request = new CreateIndexRequest.Builder()
                .index(productIndex)
                .settings(s -> s
                        .numberOfShards("3")
                        .numberOfReplicas("2")
                )
                .mappings(m -> m
                        .properties("id", p -> p.long_(l -> l))
                        .properties("name", p -> p.text(t -> t
                                .analyzer("ik_max_word")
                                .searchAnalyzer("ik_smart")
                        ))
                        .properties("description", p -> p.text(t -> t
                                .analyzer("ik_max_word")
                                .searchAnalyzer("ik_smart")
                        ))
                        .properties("price", p -> p.double_(d -> d))
                        .properties("sales", p -> p.long_(l -> l))
                        .properties("categoryId", p -> p.long_(l -> l))
                        .properties("brandId", p -> p.long_(l -> l))
                        .properties("createTime", p -> p.date(d -> d
                                .format("yyyy-MM-dd HH:mm:ss")
                        ))
                        .properties("skus", p -> p.nested(n -> n
                                .properties("id", p2 -> p2.long_(l -> l))
                                .properties("price", p2 -> p2.double_(d -> d))
                        ))
                        .properties("attributes", p -> p.object(o -> o))
                )
                .build();
        
        // 执行创建索引请求
        CreateIndexResponse response = esClient.indices().create(request);
        
        if (response.acknowledged()) {
            System.out.println("商品索引创建成功: " + productIndex);
        } else {
            System.out.println("商品索引创建失败: " + productIndex);
        }
    }
    
    /**
     * 构建商品索引映射
     */
    private String buildProductMapping() {
        Map<String, Object> mapping = new HashMap<>();
        Map<String, Object> properties = new HashMap<>();
        
        // 商品ID
        Map<String, Object> idField = new HashMap<>();
        idField.put("type", "long");
        properties.put("id", idField);
        
        // 商品名称
        Map<String, Object> nameField = new HashMap<>();
        nameField.put("type", "text");
        nameField.put("analyzer", "ik_max_word");
        nameField.put("search_analyzer", "ik_smart");
        properties.put("name", nameField);
        
        // 商品描述
        Map<String, Object> descriptionField = new HashMap<>();
        descriptionField.put("type", "text");
        descriptionField.put("analyzer", "ik_max_word");
        descriptionField.put("search_analyzer", "ik_smart");
        properties.put("description", descriptionField);
        
        // 商品价格
        Map<String, Object> priceField = new HashMap<>();
        priceField.put("type", "double");
        properties.put("price", priceField);
        
        // 商品销量
        Map<String, Object> salesField = new HashMap<>();
        salesField.put("type", "long");
        properties.put("sales", salesField);
        
        // 分类ID
        Map<String, Object> categoryIdField = new HashMap<>();
        categoryIdField.put("type", "long");
        properties.put("categoryId", categoryIdField);
        
        // 品牌ID
        Map<String, Object> brandIdField = new HashMap<>();
        brandIdField.put("type", "long");
        properties.put("brandId", brandIdField);
        
        // 创建时间
        Map<String, Object> createTimeField = new HashMap<>();
        createTimeField.put("type", "date");
        createTimeField.put("format", "yyyy-MM-dd HH:mm:ss");
        properties.put("createTime", createTimeField);
        
        // SKU列表 (nested类型)
        Map<String, Object> skusField = new HashMap<>();
        skusField.put("type", "nested");
        Map<String, Object> skusProperties = new HashMap<>();
        Map<String, Object> skuIdField = new HashMap<>();
        skuIdField.put("type", "long");
        skusProperties.put("id", skuIdField);
        Map<String, Object> skuPriceField = new HashMap<>();
        skuPriceField.put("type", "double");
        skusProperties.put("price", skuPriceField);
        // 其他SKU字段...
        skusField.put("properties", skusProperties);
        properties.put("skus", skusField);
        
        // 商品属性 (object类型)
        Map<String, Object> attributesField = new HashMap<>();
        attributesField.put("type", "object");
        properties.put("attributes", attributesField);
        
        mapping.put("properties", properties);
        
        // 转换为JSON字符串
        return "{\"properties\":{\"id\":{\"type\":\"long\"},\"name\":{\"type\":\"text\",\"analyzer\":\"ik_max_word\",\"search_analyzer\":\"ik_smart\"},\"description\":{\"type\":\"text\",\"analyzer\":\"ik_max_word\",\"search_analyzer\":\"ik_smart\"},\"price\":{\"type\":\"double\"},\"sales\":{\"type\":\"long\"},\"categoryId\":{\"type\":\"long\"},\"brandId\":{\"type\":\"long\"},\"createTime\":{\"type\":\"date\",\"format\":\"yyyy-MM-dd HH:mm:ss\"},\"skus\":{\"type\":\"nested\",\"properties\":{\"id\":{\"type\":\"long\"},\"price\":{\"type\":\"double\"}}},\"attributes\":{\"type\":\"object\"}}}";
    }
}